package com.ambow.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by MMM on 2017/08/22.
 * 时间操作工具
 */
public class DateUtil {
    /**
     * 获取当前unix时间戳,毫秒数
     *
     * @return
     */
    public static long GetUnixTimestampMillis() {
        return System.currentTimeMillis();
    }

    /**
     * 获取当前unix时间戳,秒数
     *
     * @return
     */
    public static long GetUnixTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 获取当前unix时间戳,秒数
     *
     * @return
     */
    public static String GetUnixTimestampMillisString() {
        return String.valueOf(GetUnixTimestampMillis());
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String GetDateNow() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * 计算得到MongoDB存储的日期，（默认情况下mongo中存储的是标准的时间，中国时间是东八区，存在mongo中少8小时，所以增加8小时）
     * http://www.iteye.com/problems/88507
     *
     * @author: Gao Peng
     * @date: 2016年5月4日 上午9:26:23
     * @param: @param
     * date
     * @param: @return
     * @return: Date
     */
    public static Date getMongoDate() {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Calendar ca = Calendar.getInstance();
//        ca.setTime(new Date());
//        ca.add(Calendar.HOUR_OF_DAY, 8);
//        return ca.getTime();
        return new Date();
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String dateToStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    /**
     * 获取天数偏差的日期
     *
     * @param diffDay
     * @return
     */
    public static String GetDiffDate(Integer diffDay) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, diffDay);
        date = calendar.getTime();
        String strDate = sdf.format(date);
        return strDate;
    }

    /**
     * 判断字符串是否合法日期型
     *
     * @param str
     * @return
     */
    public static boolean isValidDate(String str) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 获得当天的起始时间
     *
     * @return
     */
    public static String getDiffStartDate(Integer diffDay) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, diffDay);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        String strDate = sdf.format(calendar.getTime());
        return strDate;
    }

    /**
     * 获取当天截止时间
     *
     * @return
     */
    public static String getDiffEndDate(Integer diffDay) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, diffDay);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 59);
        String strDate = sdf.format(calendar.getTime());
        return strDate;
    }

    /**
     * 获取天数偏差的日期
     *
     * @param diffDay
     * @return
     */
    public static String GetDiffDateDay(Integer diffDay) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, diffDay);
        date = calendar.getTime();
        String strDate = sdf.format(date);
        return strDate;
    }

    public static final Map<Integer, Character> charMap = new HashMap<Integer, Character>();
    public static final Pattern p = Pattern.compile("^(\\d+)\\D*(\\d*)\\D*(\\d*)\\D*(\\d*)\\D*(\\d*)\\D*(\\d*)");

    static {
        charMap.put(1, 'y');
        charMap.put(2, 'M');
        charMap.put(3, 'd');
        charMap.put(4, 'H');
        charMap.put(5, 'm');
        charMap.put(6, 's');
    }

    /**
     * 任意日期字符串转换为Date，不包括无分割的纯数字（13位时间戳除外） ，日期时间为数字，年月日时分秒，但没有毫秒
     *
     * @param dateString 日期字符串
     * @return Date
     */
    public static Date stringToDate(String dateString) {
        dateString = dateString.trim().replaceAll("[a-zA-Z]", " ");
        if (Pattern.matches("^[-+]?\\d{13}$", dateString)) {//支持13位时间戳
            return new Date(Long.parseLong(dateString));
        }
        Matcher m = p.matcher(dateString);
        StringBuilder sb = new StringBuilder(dateString);
        if (m.find(0)) {//从被匹配的字符串中，充index = 0的下表开始查找能够匹配pattern的子字符串。m.matches()的意思是尝试将整个区域与模式匹配，不一样。
            int count = m.groupCount();
            for (int i = 1; i <= count; i++) {
                for (Map.Entry<Integer, Character> entry : charMap.entrySet()) {
                    if (entry.getKey() == i) {
                        sb.replace(m.start(i), m.end(i), replaceEachChar(m.group(i), entry.getValue()));
                    }
                }
            }
        } else {
            System.out.println("错误的日期格式");
            return null;
        }
        String format = sb.toString();
        SimpleDateFormat sf = new SimpleDateFormat(format);
        try {
            return sf.parse(dateString);
        } catch (ParseException e) {
            System.out.println("日期字符串转Date出错");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将指定字符串的所有字符替换成指定字符，跳过空白字符
     *
     * @param s 被替换字符串
     * @param c 字符
     * @return 新字符串
     */
    public static String replaceEachChar(String s, Character c) {
        StringBuilder sb = new StringBuilder("");
        for (Character c1 : s.toCharArray()) {
            if (c1 != ' ') {
                sb.append(String.valueOf(c));
            }
        }
        return sb.toString();
    }

    public static String str2Date2Str(String dateString) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(stringToDate(dateString));
    }

    public static long diffOfMinute(Date end,Date start){
        long diff=end.getTime()-start.getTime();
        return diff/60000;
    }

    public static void main(String[] args) {
        System.out.println(diffOfMinute(stringToDate("2109-04-26 09:27"),stringToDate("2109-04-26 09:25")));
    }
}
